package com.hcb.service.impl;

import com.hcb.pojo.Delivery;
import com.hcb.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 11314
 * @description TODO
 * @date 2022/11/9 8:31
 */
@Service
@ConditionalOnProperty(prefix = "config.redis",name = "enable",havingValue = "true")
public class UserRedisImpl extends UserServiceImpl{
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    LoginTreadLocalService loginTreadLocalService;
    String getDeliverNumKey(int userId){
        return "deliver:num:"+userId;
    }
    String getAvaterKey(int userId){
        return "avater:"+userId;
    }
    String getUserKey(){
        return "user:"+loginTreadLocalService.getUserId();
    }
    @Override
    public User getUser() {
        String key=getUserKey();
        if(redisTemplate.hasKey(key)){
            return (User) redisTemplate.opsForValue().get(key);
        }
        else {
            User user=super.getUser();
            redisTemplate.opsForValue().set(key,user);
            return user;
        }
    }

    @Override
    public boolean deliver(Delivery delivery) {
        redisTemplate.delete(getDeliverNumKey(delivery.getUserId()));
        return super.deliver(delivery);
    }

    @Override
    public int getDeliverNum(int userId) {
        String key=getDeliverNumKey(userId);
        if(redisTemplate.hasKey(key)){
            return (int) redisTemplate.opsForValue().get(key);
        }else {
            int num=super.getDeliverNum(userId);
            redisTemplate.opsForValue().set(key,num);
            return num;
        }
    }

    @Override
    public String changeAvater(MultipartFile file, Integer id) {
        redisTemplate.delete(getAvaterKey(id));
        return super.changeAvater(file, id);
    }

    @Override
    public void changeName(User user) {
        redisTemplate.delete(getUserKey());
        super.changeName(user);
    }
}
